package gen.core;

import gen.core.exceptions.GenException;
import gen.core.models.Table;

import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.app.Velocity;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class Generator {
	public void init() {
		Velocity.init();
	}

	/**
	 * 按sql语句生成代码
	 * 
	 * @param conn 数据库连接
	 * @param sqls SQL语句，可多句，分号隔开
	 * @param theTemplateString 模版语句
	 * 
	 * @return 产出的代码
	 */
	public String genBySql(Connection conn, String sqls, String theTemplateString) {
		final TableFactory aTableFactory = TableFactory.getInstance();

		List tables = new ArrayList();
		try {
			for (String sql : sqls.split(";")) {
				if(StringUtils.isBlank(sql))continue;
				
				QueryRunner run = new QueryRunner();
				ResultSetHandler<Table> h = new ResultSetHandler<Table>() {
					public Table handle(ResultSet rs) throws SQLException {
						return aTableFactory.newTable(rs);
					}
				};

				tables.add(run.query(conn, sql, h));
			}
			
			GenVelocityContext context = new GenVelocityContext();
			StringWriter sw = new StringWriter();
			context.put("Tables", tables.toArray(new Table[0]));
			Velocity.evaluate(context, sw, "Dynamical Template", theTemplateString);
			
			return sw.toString();
		} catch (Exception ex) {
			throw new GenException(ex, "Sql方式生成代码发生异常！");
		}
	}

	public String genByArrays(Object[][] theArrays, String theTemplateString) {
		GenVelocityContext context = new GenVelocityContext();
		StringWriter sw = new StringWriter();
		context.put("Arrays", theArrays);
		Velocity.evaluate(context, sw, "Dynamical Template", theTemplateString);
		return sw.toString();
	}
}
